using System.Text;
using System.Text.Json;
using System.Net.Http.Headers;
using System.Net.Http;
using System.IO;

namespace aichat.Services
{
    public class AiApiService : IAiApiService
    {
        private readonly HttpClient _httpClient;
        private readonly Dictionary<string, AiApiConfig> _apiConfigs;

        public AiApiService()
        {
            _httpClient = new HttpClient();
            _apiConfigs = LoadApiConfigs();
        }

        private Dictionary<string, AiApiConfig> LoadApiConfigs()
        {
            var configs = new Dictionary<string, AiApiConfig>();
            
            try
            {
                // 读取配置文件
                var configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "appsettings.json");
                if (File.Exists(configPath))
                {
                    var jsonContent = File.ReadAllText(configPath);
                    var configDoc = JsonDocument.Parse(jsonContent);
                    
                    if (configDoc.RootElement.TryGetProperty("AiApiSettings", out var aiSettings))
                    {
                        // OpenAI配置
                        if (aiSettings.TryGetProperty("OpenAI", out var openai) && 
                            openai.TryGetProperty("ApiKey", out var openaiKey))
                        {
                            var openaiKeyValue = openaiKey.GetString() ?? "";
                            configs["gpt-3.5-turbo"] = new AiApiConfig
                            {
                                BaseUrl = "https://api.openai.com/v1/chat/completions",
                                ApiKey = openaiKeyValue,
                                ModelName = "gpt-3.5-turbo",
                                MaxTokens = 4096
                            };
                            
                            configs["gpt-4"] = new AiApiConfig
                            {
                                BaseUrl = "https://api.openai.com/v1/chat/completions",
                                ApiKey = openaiKeyValue,
                                ModelName = "gpt-4",
                                MaxTokens = 8192
                            };
                        }
                        
                        // Anthropic配置
                        if (aiSettings.TryGetProperty("Anthropic", out var anthropic) && 
                            anthropic.TryGetProperty("ApiKey", out var anthropicKey))
                        {
                            var anthropicKeyValue = anthropicKey.GetString() ?? "";
                            configs["claude-3-sonnet"] = new AiApiConfig
                            {
                                BaseUrl = "https://api.anthropic.com/v1/messages",
                                ApiKey = anthropicKeyValue,
                                ModelName = "claude-3-sonnet-20240229",
                                MaxTokens = 4096
                            };
                        }
                        
                        // DeepSeek配置
                        if (aiSettings.TryGetProperty("DeepSeek", out var deepseek) && 
                            deepseek.TryGetProperty("ApiKey", out var deepseekKey))
                        {
                            var deepseekKeyValue = deepseekKey.GetString() ?? "";
                            configs["deepseek-chat"] = new AiApiConfig
                            {
                                BaseUrl = "https://api.deepseek.com/v1/chat/completions",
                                ApiKey = deepseekKeyValue,
                                ModelName = "deepseek-chat",
                                MaxTokens = 8192
                            };
                        }
                        
                        // 阿里云配置
                        if (aiSettings.TryGetProperty("Alibaba", out var alibaba) && 
                            alibaba.TryGetProperty("ApiKey", out var alibabaKey))
                        {
                            var alibabaKeyValue = alibabaKey.GetString() ?? "";
                            configs["qwen-plus"] = new AiApiConfig
                            {
                                BaseUrl = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",
                                ApiKey = alibabaKeyValue,
                                ModelName = "qwen-plus",
                                MaxTokens = 4096
                            };
                        }
                    }
                }
                
                System.Diagnostics.Debug.WriteLine($"加载了 {configs.Count} 个API配置");
                foreach (var config in configs)
                {
                    System.Diagnostics.Debug.WriteLine($"模型: {config.Key}, API密钥: {config.Value.ApiKey.Substring(0, Math.Min(10, config.Value.ApiKey.Length))}...");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载API配置失败: {ex.Message}");
            }
            
            return configs;
        }

        public async Task<string> GetStreamingResponseAsync(string message, string modelName, IProgress<string> progress)
        {
            if (!_apiConfigs.TryGetValue(modelName, out var config))
            {
                throw new ArgumentException($"不支持的AI模型: {modelName}");
            }

            if (string.IsNullOrEmpty(config.ApiKey))
            {
                throw new InvalidOperationException($"未配置 {modelName} 的API密钥");
            }

            try
            {
                return modelName switch
                {
                    "gpt-3.5-turbo" or "gpt-4" => await CallOpenAIAsync(message, config, progress),
                    "claude-3-sonnet" => await CallAnthropicAsync(message, config, progress),
                    "deepseek-chat" => await CallDeepSeekAsync(message, config, progress),
                    "qwen-plus" => await CallAlibabaAsync(message, config, progress),
                    _ => throw new ArgumentException($"不支持的AI模型: {modelName}")
                };
            }
            catch (Exception ex)
            {
                throw new Exception($"调用AI API失败: {ex.Message}", ex);
            }
        }

        public bool IsConfigured()
        {
            return _apiConfigs.Values.Any(config => !string.IsNullOrEmpty(config.ApiKey));
        }

        private async Task<string> CallOpenAIAsync(string message, AiApiConfig config, IProgress<string> progress)
        {
            var requestBody = new
            {
                model = config.ModelName,
                messages = new[]
                {
                    new { role = "user", content = message }
                },
                stream = true,
                max_tokens = config.MaxTokens
            };

            var request = new HttpRequestMessage(HttpMethod.Post, config.BaseUrl)
            {
                Content = new StringContent(JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json")
            };
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", config.ApiKey);

            var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
            response.EnsureSuccessStatusCode();

            var responseBuilder = new StringBuilder();
            using var stream = await response.Content.ReadAsStreamAsync();
            using var reader = new StreamReader(stream);

            while (!reader.EndOfStream)
            {
                var line = await reader.ReadLineAsync();
                if (string.IsNullOrEmpty(line)) continue;

                if (line.StartsWith("data: "))
                {
                    var data = line.Substring(6);
                    if (data == "[DONE]") break;

                    try
                    {
                        var jsonDoc = JsonDocument.Parse(data);
                        var choices = jsonDoc.RootElement.GetProperty("choices");
                        if (choices.GetArrayLength() > 0)
                        {
                            var delta = choices[0].GetProperty("delta");
                            if (delta.TryGetProperty("content", out var content))
                            {
                                var contentText = content.GetString();
                                if (!string.IsNullOrEmpty(contentText))
                                {
                                    responseBuilder.Append(contentText);
                                    var currentText = responseBuilder.ToString();
                                    System.Diagnostics.Debug.WriteLine($"收到文本片段: '{contentText}'，当前总长度: {currentText.Length}");
                                    progress?.Report(currentText);
                                    
                                    // 添加小延迟，让打字机效果更明显
                                    await Task.Delay(30);
                                }
                            }
                        }
                    }
                    catch (JsonException)
                    {
                        // 忽略无效的JSON
                    }
                }
            }

            return responseBuilder.ToString();
        }

        private async Task<string> CallAnthropicAsync(string message, AiApiConfig config, IProgress<string> progress)
        {
            var requestBody = new
            {
                model = config.ModelName,
                max_tokens = config.MaxTokens,
                messages = new[]
                {
                    new { role = "user", content = message }
                },
                stream = true
            };

            var request = new HttpRequestMessage(HttpMethod.Post, config.BaseUrl)
            {
                Content = new StringContent(JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json")
            };
            request.Headers.Add("x-api-key", config.ApiKey);
            request.Headers.Add("anthropic-version", "2023-06-01");

            var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
            response.EnsureSuccessStatusCode();

            var responseBuilder = new StringBuilder();
            using var stream = await response.Content.ReadAsStreamAsync();
            using var reader = new StreamReader(stream);

            while (!reader.EndOfStream)
            {
                var line = await reader.ReadLineAsync();
                if (string.IsNullOrEmpty(line)) continue;

                if (line.StartsWith("data: "))
                {
                    var data = line.Substring(6);
                    if (data == "[DONE]") break;

                    try
                    {
                        var jsonDoc = JsonDocument.Parse(data);
                        if (jsonDoc.RootElement.TryGetProperty("type", out var type) && type.GetString() == "content_block_delta")
                        {
                            if (jsonDoc.RootElement.TryGetProperty("delta", out var delta) && 
                                delta.TryGetProperty("text", out var text))
                            {
                                var textContent = text.GetString();
                                if (!string.IsNullOrEmpty(textContent))
                                {
                                    responseBuilder.Append(textContent);
                                    progress?.Report(responseBuilder.ToString());
                                    
                                    await Task.Delay(30);
                                }
                            }
                        }
                    }
                    catch (JsonException)
                    {
                        // 忽略无效的JSON
                    }
                }
            }

            return responseBuilder.ToString();
        }

        private async Task<string> CallDeepSeekAsync(string message, AiApiConfig config, IProgress<string> progress)
        {
            var requestBody = new
            {
                model = config.ModelName,
                messages = new[]
                {
                    new { role = "user", content = message }
                },
                stream = true,
                max_tokens = config.MaxTokens
            };

            var request = new HttpRequestMessage(HttpMethod.Post, config.BaseUrl)
            {
                Content = new StringContent(JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json")
            };
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", config.ApiKey);

            var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
            response.EnsureSuccessStatusCode();

            var responseBuilder = new StringBuilder();
            using var stream = await response.Content.ReadAsStreamAsync();
            using var reader = new StreamReader(stream);

            while (!reader.EndOfStream)
            {
                var line = await reader.ReadLineAsync();
                if (string.IsNullOrEmpty(line)) continue;

                if (line.StartsWith("data: "))
                {
                    var data = line.Substring(6);
                    if (data == "[DONE]") break;

                    try
                    {
                        var jsonDoc = JsonDocument.Parse(data);
                        var choices = jsonDoc.RootElement.GetProperty("choices");
                        if (choices.GetArrayLength() > 0)
                        {
                            var delta = choices[0].GetProperty("delta");
                            if (delta.TryGetProperty("content", out var content))
                            {
                                var contentText = content.GetString();
                                if (!string.IsNullOrEmpty(contentText))
                                {
                                    responseBuilder.Append(contentText);
                                    progress?.Report(responseBuilder.ToString());
                                    
                                    await Task.Delay(30);
                                }
                            }
                        }
                    }
                    catch (JsonException)
                    {
                        // 忽略无效的JSON
                    }
                }
            }

            return responseBuilder.ToString();
        }

        private async Task<string> CallAlibabaAsync(string message, AiApiConfig config, IProgress<string> progress)
        {
            var requestBody = new
            {
                model = config.ModelName,
                messages = new[]
                {
                    new { role = "user", content = message }
                },
                stream = true,
                max_tokens = config.MaxTokens
            };

            var request = new HttpRequestMessage(HttpMethod.Post, config.BaseUrl)
            {
                Content = new StringContent(JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json")
            };
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", config.ApiKey);

            var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
            response.EnsureSuccessStatusCode();

            var responseBuilder = new StringBuilder();
            using var stream = await response.Content.ReadAsStreamAsync();
            using var reader = new StreamReader(stream);

            while (!reader.EndOfStream)
            {
                var line = await reader.ReadLineAsync();
                if (string.IsNullOrEmpty(line)) continue;

                if (line.StartsWith("data: "))
                {
                    var data = line.Substring(6);
                    if (data == "[DONE]") break;

                    try
                    {
                        var jsonDoc = JsonDocument.Parse(data);
                        var choices = jsonDoc.RootElement.GetProperty("choices");
                        if (choices.GetArrayLength() > 0)
                        {
                            var delta = choices[0].GetProperty("delta");
                            if (delta.TryGetProperty("content", out var content))
                            {
                                var contentText = content.GetString();
                                if (!string.IsNullOrEmpty(contentText))
                                {
                                    responseBuilder.Append(contentText);
                                    progress?.Report(responseBuilder.ToString());
                                    
                                    await Task.Delay(30);
                                }
                            }
                        }
                    }
                    catch (JsonException)
                    {
                        // 忽略无效的JSON
                    }
                }
            }

            return responseBuilder.ToString();
        }

        private class AiApiConfig
        {
            public string BaseUrl { get; set; } = "";
            public string ApiKey { get; set; } = "";
            public string ModelName { get; set; } = "";
            public int MaxTokens { get; set; } = 2048;
        }
    }
} 